package phototransfer.model.udp;

import android.util.Log;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UdpConnection {
   public static final String TAG = UdpConnection.class.getName();
   private DatagramSocket mDatagramSocketClient = null;
   private DatagramSocket mDatagramSocketServer = null;
   private String mServerIp = "255.255.255.255";
   private int mServerPort = 8888;

   public void start(int udpPort) {
      this.mServerPort = udpPort;

      try {
         this.mDatagramSocketClient = new DatagramSocket();
         this.mDatagramSocketClient.setBroadcast(true);
         this.mDatagramSocketServer = new DatagramSocket(this.mServerPort);
      } catch (SocketException var3) {
         var3.printStackTrace();
         Log.d(TAG, "start: failed " + var3);
      }

      Log.d(TAG, "start: success");
   }

   public void close() {
      if (null != this.mDatagramSocketServer && this.mDatagramSocketServer.isConnected()) {
         this.mDatagramSocketServer.disconnect();
         this.mDatagramSocketServer = null;
      }

      if (null != this.mDatagramSocketClient && this.mDatagramSocketClient.isConnected()) {
         this.mDatagramSocketClient.disconnect();
         this.mDatagramSocketClient = null;
      }

   }

   public void send(byte[] buf, int len) throws IOException {
      DatagramPacket sendPacket = new DatagramPacket(buf, len, InetAddress.getByName(this.mServerIp), this.mServerPort);
      this.mDatagramSocketServer.send(sendPacket);
   }

   public void sendboardcast(byte[] buf, int len) throws IOException {
      this.send(buf, len, InetAddress.getByName("255.255.255.255"));
   }

   public void send(byte[] buf, int len, InetAddress ip) throws IOException {
      DatagramPacket datagramPacket = new DatagramPacket(buf, len, ip, this.mServerPort);
      this.mDatagramSocketServer.send(datagramPacket);
   }

   public DatagramPacket recv(byte[] buff, int len) throws IOException {
      if (null == this.mDatagramSocketServer) {
         return null;
      } else {
         DatagramPacket packet = new DatagramPacket(buff, len);
         this.mDatagramSocketServer.receive(packet);
         return packet;
      }
   }

   public void setTimeOut(int i) throws SocketException {
      if (null != this.mDatagramSocketServer) {
         this.mDatagramSocketServer.setSoTimeout(i);
      }

   }
}
